<route lang="json5" type="home">
{
  layout: 'tabbar',
  style: {
    navigationBarTitleText: '梦瑶诗歌',
    navigationStyle: 'default',
  },
  needLogin: 'true',
}
</route>

<template>
  <view class="container">
    <!-- 每日一诗弹窗 -->
    <wd-popup
      v-model="showPopup"
      position="center"
      custom-style="background-color: transparent;"
      :close-on-click-modal="false"
    >
      <!-- 加载状态遮罩 -->
      <view v-if="!backgroundLoaded" class="loading-overlay">
        <wd-icon
          name="close"
          size="32rpx"
          custom-class="close-loading-icon"
          @click="showPopup = false"
        />
        <view class="center-content">
          <wd-loading size="48rpx" color="#4a90e2"></wd-loading>
          <text class="loading-text">正在加载每日一诗</text>
        </view>
      </view>

      <view class="poem-popup" :style="{ backgroundImage: 'url(' + everydayPoem.base64 + ')' }">
        <wd-icon name="close" size="24px" custom-class="close-icon" @click="showPopup = false" />
        <view class="horizontal-layout">
          <!-- 标题和作者信息 -->
          <view class="poem-header">
            <text class="poem-title">{{ everydayPoem.title }}</text>
            <view class="poem-author-info">
              <text class="poem-dynasty">{{ everydayPoem.dynasty }}</text>
              <text class="poem-author">{{ everydayPoem.author }}</text>
            </view>
          </view>

          <!-- 诗歌内容 -->
          <view class="poem-content">
            <view
              v-for="(sentence, index) in everydayPoem.content"
              :key="index"
              class="poem-sentence"
              :style="{ fontSize: `${everydayPoem.fontSize}rpx` }"
            >
              {{ sentence }}
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
    <!-- 诗歌列表 -->
    <view class="poem-list">
      <view
        v-for="(item, index) in currentPoemList"
        :key="index"
        class="poem-card"
        @click="navigateToDetail(item)"
      >
        <view class="card-content">
          <text class="title">{{ item.name }}</text>
          <text class="subtitle">{{ item.subTitle }}</text>
          <view class="tags">
            <text
              v-for="(tag, i) in item.representativePoet.split(',')"
              :key="i"
              class="tag"
              :class="['tag' + ((i % 3) + 1)]"
            >
              {{ tag }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态提示 -->
    <view class="loadmore">
      <text v-if="loadState === 'loading'">加载中...</text>
      <text v-else-if="loadState === 'finished'">没有更多了</text>
      <text v-else-if="loadState === 'error'" @click="loadPoetryTypes" class="error-tip">
        加载失败，点击重试
      </text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { http } from '@/utils/http'
import { useAuthHeaders, checkTokenIsValid } from '@/utils/token'
import { EverydayPoemItem, type PoemType } from '@/api/poem.typings'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { usePageAuth } from '@/hooks/usePageAuth'

// 服务器地址
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

// 数据状态
const currentPoemList = ref<PoemType[]>([])
const totalPoemList = ref<PoemType[]>([])
const page = ref(1)
const pageSize = 10
const total = ref(0) // 总数据量
// loadmore 状态：'loading' | 'finished' | 'error'
const loadState = ref<'loading' | 'finished' | 'error'>('loading')
// 每日一诗弹窗相关
const showPopup = ref(true) // 默认显示弹窗
const backgroundLoaded = ref(false)
const everydayPoem = ref<EverydayPoemItem>({
  author: '',
  dynasty: '',
  title: '',
  content: [],
  base64: '',
  fontSize: '',
})

// 加载诗歌类型（分页）
const loadPoetryTypes = async () => {
  loadState.value = 'loading'

  try {
    const header = useAuthHeaders()
    // console.log(header)
    const res = await http.get<PoemType[]>(`${API_BASE_URL}/api/v1/poetry/type`, {}, header)
    // console.log(res)

    if (res.code === 200) {
      totalPoemList.value = res.data || []
      total.value = res.data.length || 0
      currentPoemList.value = totalPoemList.value.slice(
        (page.value - 1) * pageSize,
        page.value * pageSize,
      )
      // 更新分页状态
      if (totalPoemList.value.length <= pageSize) {
        loadState.value = 'finished'
      } else {
        loadState.value = 'loading'
      }
    } else {
      loadState.value = 'error'
    }
  } catch (e) {
    console.error(e)
    loadState.value = 'error'
  }
}

// 获取每日一诗数据
const getEverydayPoem = async () => {
  backgroundLoaded.value = false // 重置加载状态
  try {
    const res = await http.get<EverydayPoemItem>(`${API_BASE_URL}/api/v1/poetry/everyday`, {}, {})

    if (res.code === 200) {
      everydayPoem.value = res.data || everydayPoem.value

      // 如果 base64 开头不是标准的 data:image/，尝试修正
      if (everydayPoem.value.base64?.startsWith('data:application/octet-stream;')) {
        everydayPoem.value.base64 = everydayPoem.value.base64.replace(
          'data:application/octet-stream;',
          'data:image/jpeg;',
        )
      }
      checkImageLoaded(everydayPoem.value.base64)
      const maxLength = Math.max(...everydayPoem.value.content.map((s) => s.length))
      if (maxLength > 20) {
        everydayPoem.value.fontSize = '30' // 如果句子很长，统一缩小字体
      } else {
        everydayPoem.value.fontSize = '34' // 正常字体大小
      }
    } else {
      console.error('请求后端接口获取每日一诗数据失败', res.msg)
      backgroundLoaded.value = true // 确保不会卡在加载状态
    }
  } catch (e) {
    console.error('获取每日一诗失败', e)
    backgroundLoaded.value = true // 确保不会卡在加载状态
  }
}

const checkImageLoaded = (base64: string) => {
  // 在小程序中获取临时文件路径
  const path = `data:image/jpeg;base64,${base64.split('base64,')[1]}`

  // 使用uni.getImageInfo API检查图片
  uni.getImageInfo({
    src: path,
    success: () => {
      backgroundLoaded.value = true
    },
    fail: () => {
      backgroundLoaded.value = true
    },
  })
}
// 页面初次加载
onShow(async () => {
  usePageAuth()
  loadPoetryTypes()
})

onLoad(async () => {
  getEverydayPoem()
  showPopup.value = await checkTokenIsValid()
  backgroundLoaded.value = !showPopup.value
})

uni.$on('loginStatusChanged', async (status: boolean) => {
  if (status) {
    // 登录成功后刷新数据
    await loadPoetryTypes()
    await getEverydayPoem()
  }
})

onUnmounted(() => {
  uni.$off('loginStatusChanged')
})

onReachBottom(() => {
  if (currentPoemList.value.length < total.value) {
    loadState.value = 'loading'
    page.value += 1
    currentPoemList.value.push(
      ...totalPoemList.value.slice((page.value - 1) * pageSize, page.value * pageSize),
    )
  } else {
    loadState.value = 'finished'
  }
})

// 跳转详情
function navigateToDetail(item: PoemType) {
  uni.navigateTo({
    url: `/pages/poem/poem?collection=${item.type}`,
  })
}
</script>

<style lang="scss" scoped>
.container {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
}

.poem-list {
  display: grid;
  gap: 20rpx;
  flex: 1;
}

.poem-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 6rpx;
    height: 100%;
    background: #4a90e2;
  }

  &:active {
    transform: translateY(4rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 1rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #7f8c8d;
  line-height: 1.6;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 8rpx;
}

.tag {
  background: rgba(74, 144, 226, 0.1);
  color: #4a90e2;
  padding: 6rpx 20rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  font-weight: 500;

  /* 三种颜色的标签样式 */
  &.tag2 {
    background: rgba(52, 199, 89, 0.1);
    color: #34c759;
  }

  &.tag3 {
    background: rgba(255, 59, 48, 0.1);
    color: #ff3b30;
  }
}

.loadmore {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 28rpx;

  .error-tip {
    color: #ff3b30;
    text-decoration: underline;
  }
}

/* 响应式布局 - 平板/PC */
@media (min-width: 768px) {
  .poem-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 响应式布局 - 大屏 */
@media (min-width: 1024px) {
  .poem-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

// 每日一诗弹窗样式
.poem-popup {
  width: 600rpx;
  height: 800rpx;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  position: relative;
  padding: 40rpx;
  box-sizing: border-box;
  color: #333; // 文字颜色，根据背景可能需要调整
  filter: drop-shadow(0 10rpx 30rpx rgba(0, 0, 0, 0.3)); // 增加立体感
  /* 添加遮罩层 */
  .overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5); /* 半透明黑色遮罩 */
    border-radius: 16rpx;
    z-index: 1;
  }
}

.close-icon {
  position: fixed;
  top: 40rpx;
  right: 40rpx;
  color: #fff;
  z-index: 100; /* 增加层级值 */
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  padding: 8rpx;
  text-shadow: 0 0 4rpx rgba(0, 0, 0, 0.8);
}

.horizontal-layout {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 60rpx 40rpx;
  align-items: center;
  justify-content: center;
  color: #fff;
  position: relative;
  z-index: 10;
  gap: 40rpx;
}

.poem-header {
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 16rpx;

  .poem-title {
    font-size: 48rpx;
    font-weight: bold;
    letter-spacing: 4rpx;
    text-shadow:
      0 0 8rpx rgba(0, 0, 0, 0.9),
      0 0 16rpx rgba(0, 0, 0, 0.7);
  }

  .poem-author-info {
    display: flex;
    justify-content: center;
    gap: 20rpx;
    font-size: 32rpx;
    text-shadow:
      0 0 6rpx rgba(0, 0, 0, 0.9),
      0 0 12rpx rgba(0, 0, 0, 0.7);
  }
}

.poem-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24rpx;
  width: 100%;

  .poem-line {
    display: flex;
    gap: 5rpx;
    flex-wrap: wrap;
    justify-content: center;
  }

  .poem-sentence {
    font-size: 35rpx;
    font-weight: 500;
    text-align: center;
    text-shadow:
      0 0 6rpx rgba(0, 0, 0, 0.9),
      0 0 12rpx rgba(0, 0, 0, 0.7);
    letter-spacing: 1px;
    line-height: 1.6;
    max-width: 95%;
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.95); /* 更透明的背景 */
  border-radius: 16rpx;
  z-index: 1000; /* 确保位于内容上方 */

  /* 固定按钮位置 */
  .close-loading-icon {
    position: absolute;
    top: 24rpx;
    left: 24rpx;
    z-index: 20;
    background-color: rgba(0, 0, 0, 0.05); /* 轻微背景 */
    border-radius: 50%;
    padding: 8rpx;
  }

  /* 居中效果 */
  .center-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%; /* 占据全部宽度 */
  }

  .loading-text {
    font-size: 32rpx;
    color: #4a90e2;
    margin-top: 40rpx; /* 增加间距 */
    font-weight: 500;
  }
}
</style>
